import warnings
from time import sleep

import allure
import logging

import pytest
from selenium.common.exceptions import NoSuchElementException

from utils.execl_Util import execl_Util

logger = logging.getLogger()


# 获取el-message控件中的上下文，并且获取el-message的控件种类（error、warning、success等等）
@allure.step('开始查找 el-message 控件')
def get_el_message(sele):
    content = None
    try:
        logger.info('开始查找 el-message 控件')
        el_message = sele.locator('xpath', "//*[contains(@class,'el-message--')]")
        if el_message:
            class_names = el_message.get_attribute('class').split(' ')
            hint_type = class_names[1][12:len(class_names[1])]
            content = {hint_type: sele.get_text('xpath', "//*[@class='el-message__content']")}
            allure.attach(sele.screenshot(), content.get(hint_type), allure.attachment_type.PNG)
        return content
    except NoSuchElementException as e:
        logger.info('未发现异常 el-message 控件')


# 执行流程，通过该方法可以通过excel模版进行覆盖
@allure.step('执行步骤')
def service(sele, file_url, sheet_name):
    try:
        logger.info('开始表执行流程:' + sheet_name)
        sheet = execl_Util.get_sheet(file_url, sheet_name)
        data_list = execl_Util.get_sheet_data(sheet)
        data_list.pop(0)
        for row in data_list:
            with allure.step('描述:{}，执行方法：{}，定位方式：{}，路径：{}，输入值：{}'.format(row[0], row[1], row[2], row[3], row[4])):
                logger.info('描述:{}，执行方法：{}，定位方式：{}，路径：{}，输入值：{}'.format(row[0], row[1], row[2], row[3], row[4]))
            sele.methodcaller(method_name=row[1], find_command=row[2], name=row[3], value=row[4])
            # 处理异常el_message控件
            if row[1] == 'click':
                sleep(1)
                message = get_el_message(sele)
                if not message is None:
                    print(message)
                    if list(message.keys())[0] == 'warning':
                        assert warning(message) == 1
                        logger.error(str(message) + 'info:' + str(row))
                        pytest.fail(str(message) + 'info:' + str(row))
                    if list(message.keys())[0] == 'error':
                        logger.error(str(message) + 'info:' + str(row))
                        pytest.xfail(str(message) + 'info:' + str(row))
    except Exception as e:
        allure.attach(sele.screenshot(), row, allure.attachment_type.PNG)
        logger.error(e)
        pytest.xfail(str(e))


def warning(message):
    with pytest.warns(UserWarning):
        warnings.warn(str(message), UserWarning)
    return 1
